<script setup lang="ts">
import { ref, watch, reactive, computed } from "vue";
import { ElMessage } from "element-plus";
import { createAdmin, updateAdmin } from "@/api/admin";
import type { Role } from "@/api/role";

defineOptions({
  name: "UserForm"
});

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  user: {
    type: Object,
    default: () => ({})
  },
  type: {
    type: String,
    default: "add"
  },
  roleOptions: {
    type: Array as () => Role[],
    default: () => []
  }
});

const emit = defineEmits(["update:visible", "save"]);

interface UserType {
  id?: number;
  username: string;
  nickname: string;
  password?: string;
  confirmPassword?: string;
  phone: string;
  status: number;
  role_id: number;
  role_name?: string;
  avatar?: string;
}

// 初始表单数据
const defaultFormData = {
  id: undefined,
  username: "",
  nickname: "",
  password: "",
  confirmPassword: "",
  phone: "",
  status: 1,
  role_id: 0,
  role_name: "",
  avatar: ""
};

// 表单数据
const formData = reactive<UserType>({ ...defaultFormData });

const formRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "用户名长度应为2-20个字符", trigger: "blur" }
  ],
  nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  password: [
    {
      required: props.type === 'add',
      message: "请输入密码",
      trigger: "blur"
    },
    { min: 6, message: "密码不能少于6个字符", trigger: "blur" }
  ],
  confirmPassword: [
    {
      required: props.type === 'add',
      message: "请再次输入密码",
      trigger: "blur"
    },
    {
      validator: (rule, value, callback) => {
        if (props.type === "add" || (formData.password && formData.password.length > 0)) {
          if (value !== formData.password) {
            callback(new Error("两次输入密码不一致"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号格式", trigger: "blur" }
  ],
  role_id: [
  ]
};

const formRef = ref();
const submitLoading = ref(false);

// 监听visible变化，当弹窗打开时重置表单
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      // 弹窗打开时，根据props.user设置表单数据
      if (props.user) {
        // 重置表单数据
        Object.assign(formData, defaultFormData);
        // 然后设置新的值
        Object.assign(formData, {
          ...props.user,
          password: "",
          confirmPassword: ""
        });
      }
    }
  }
);

// 监听user变化，更新表单数据
watch(
  () => props.user,
  (newVal) => {
    if (newVal && props.visible) {
      // 重置表单数据
      Object.assign(formData, defaultFormData);

      // 处理用户数据，适配不同来源的格式
      const userData = { ...newVal };

      // 如果是从登录接口返回的数据格式
      if (newVal.permissions && Array.isArray(newVal.permissions)) {
        console.log('检测到登录接口返回的用户数据格式');
      }

      // 然后设置新的值
      Object.assign(formData, {
        ...userData,
        password: "",
        confirmPassword: ""
      });

      console.log('表单数据已更新:', formData);
    }
  },
  { deep: true }
);

// 监听角色ID变化，自动更新角色名称
watch(
  () => formData.role_id,
  (newRoleId) => {
    if (newRoleId) {
      const selectedRole = props.roleOptions.find(role => role.id === newRoleId);
      if (selectedRole) {
        formData.role_name = selectedRole.name;
      }
    } else {
      formData.role_name = '';
    }
  }
);

const dialogTitle = computed(() => props.type === "add" ? "添加管理员" : "编辑管理员");

// 关闭弹窗
const closeDialog = () => {
  // 重置表单数据
  Object.assign(formData, defaultFormData);
  // 关闭弹窗
  emit("update:visible", false);
};

// 保存
const saveUser = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        submitLoading.value = true;

        if (props.type === "add") {
          // 创建新管理员，需要按照API要求的类型构建数据
          const createData = {
            username: formData.username,
            password: formData.password || '',  // 确保存在
            nickname: formData.nickname,
            phone: formData.phone,
            status: formData.status,
            role_id: formData.role_id
          };

          // 验证必填字段
          if (!createData.password) {
            ElMessage.error("密码不能为空");
            submitLoading.value = false;
            return;
          }

          const res = await createAdmin(createData);
          if (res.code === 0) {
            ElMessage.success("添加成功");
            // 重置表单数据
            Object.assign(formData, defaultFormData);
            // 通知父组件保存成功并关闭弹窗
            emit("save", formData);
            emit("update:visible", false);
          } else {
            ElMessage.error(res.msg || "添加失败");
          }
        } else {
          // 编辑模式，按照API要求的类型构建数据
          if (!formData.id) {
            ElMessage.error("用户ID不能为空");
            submitLoading.value = false;
            return;
          }

          // 获取角色名称（如果不存在）
          if (!formData.role_name && formData.role_id) {
            const selectedRole = props.roleOptions.find(role => role.id === formData.role_id);
            if (selectedRole) {
              formData.role_name = selectedRole.name;
            }
          }

          // 按照AdminUpdateRequest规范构建数据
          const updateData = {
            id: formData.id,
            username: formData.username,
            nickname: formData.nickname,
            phone: formData.phone,
            status: formData.status,
            role_id: formData.role_id,
            role_name: formData.role_name || '',
            avatar: formData.avatar || ""
          };

          console.log('提交更新数据:', updateData);

          // 更新管理员
          const res = await updateAdmin(updateData);

          if (res.code === 0) {
            ElMessage.success("更新成功");
            // 重置表单数据
            Object.assign(formData, defaultFormData);
            // 通知父组件保存成功并关闭弹窗
            emit("save", formData);
            emit("update:visible", false);
          } else {
            ElMessage.error(res.msg || "更新失败");
          }
        }
      } catch (error) {
        console.error("保存管理员失败:", error);
        ElMessage.error("操作失败，请稍后重试");
      } finally {
        submitLoading.value = false;
      }
    }
  });
};
</script>

<template>
  <el-dialog :model-value="visible" @update:model-value="dialogVisible => emit('update:visible', dialogVisible)"
    :title="dialogTitle" width="500px" append-to-body destroy-on-close @closed="closeDialog">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" placeholder="请输入用户名" :disabled="type === 'edit'" />
        <div v-if="type === 'edit'" class="form-tip">用户名不可修改</div>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="formData.nickname" placeholder="请输入昵称" />
      </el-form-item>
      <!-- 密码字段只在新增模式显示 -->
      <template v-if="type === 'add'">
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="formData.confirmPassword" type="password" placeholder="请再次输入密码" show-password />
        </el-form-item>
      </template>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="角色" prop="role_id">
        <el-select v-model="formData.role_id" placeholder="请选择角色" style="width: 100%">
          <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveUser" :loading="submitLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>